<?php

namespace app\factory\logic;

use app\common\exception\LogicException;
use app\model\Machine;
use app\model\MachineVersion;
use stdClass;

class MachineLogic
{
    protected Machine $model;
    protected int $factory_id;

    public function __construct()
    {
        $this->model = new Machine();
        $this->factory_id = request()->factory_info['factory_id'];
    }

    /**
     * @Description 获取机器信息
     * @author: zj
     * @param string $machine_code
     * @time 2024/03/11 12:28:11
     * @return mixed
     */
    public function getInfo(string $machine_code)
    {
        $info = $this->model
            ->field('id,factory_id,machine_code,now_version_id,target_version_id,force,create_time')
            ->where('factory_id',$this->factory_id)
            ->where('delete_time',$this->model::IS_DELETE_NO)
            ->where('machine_code',$machine_code)
            ->find();
        if (!$info) {
            throw new LogicException('code: '.$machine_code.'的机器不存在');
        }
        $machineInfo = $info->toArray();

        //判断版本
        $versionModel = new MachineVersion();
        $versionInfo = $versionModel->field('version_name,remark,url')
            ->where('id', $machineInfo['target_version_id'])
            ->where('delete_time', $versionModel::IS_DELETE_NO)
            ->find();
        if ($versionInfo) {
            $machineInfo['version_data'] = [
                'version_name' => $versionInfo['version_name'],
                'remark' => $versionInfo['remark'],
                'url' => $versionInfo['url'],
            ];
        } else {
            $machineInfo['version_data'] = new stdClass();
        }

        return $machineInfo;
    }

    /**
     * @Description 机器信息上报
     * @author: zj
     * @param string $machine_code
     * @param string $machine_version
     * @time 2024/03/11 15:49:26
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function report(string $machine_code, string $machine_version)
    {
        $machineId = $this->model->checkExistByCode($this->factory_id, $machine_code);
        if (!$machineId) {
            throw new LogicException('machine_code不存在');
        }

        //判断版本
        $versionModel = new MachineVersion();
        $versionInfo = $versionModel->field('id')
            ->where('version_name', $machine_version)
            ->find();
        if (!$versionInfo) {
            throw new LogicException('版本不存在');
        }

        $this->model->where('id', $machineId)
            ->update([
                'now_version_id' => $versionInfo['id'],
                'update_time' => request()->time()
            ]);

        return true;
    }
}